package com.example.backend2.inteceptor;

import com.example.backend2.context.LoginMemberContext;
import com.example.backend2.domain.Role;
import com.example.backend2.domain.User;
import com.example.backend2.exception.BusinessException;
import com.example.backend2.exception.BusinessExceptionEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class RoleInterceptor {

    @Before("@annotation(com.example.backend2.domain.Role)")
    public void checkAuthorization(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Role roleAnnotation = method.getAnnotation(Role.class);
        int requiredRole = roleAnnotation.value();
        if (requiredRole == Role.GUEST) {
            return;
        } else {
            User member = LoginMemberContext.getMember();
            System.out.println(member);
            if (member == null) {
                throw new BusinessException(BusinessExceptionEnum.NO_AUTHORIZED);
            }
        }
    }
}
